<template>
  <el-card class="holdings-card">
    <template #header>
      <div class="card-header">
        <span>持仓详情</span>
        <el-button link @click="handleRefresh">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
      </div>
    </template>

    <el-table :data="holdingsData" stripe style="width: 100%" :loading="loading || props.externalLoading"
      :default-sort="{ prop: 'marketValue', order: 'descending' }" v-loading="loading || props.externalLoading"
      element-loading-text="正在加载持仓数据..." element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.1)"
      :empty-text="loading || props.externalLoading ? '加载中...' : '暂无持仓数据'" :show-header="true" :border="false"
      :highlight-current-row="true">
      <!-- <el-table-column prop="stockCode" label="股票代码" width="120" sortable>
        <template #default="scope">
          <span class="stock-code">{{ scope.row.stockCode }}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="stockName" label="股票名称" width="150" sortable>
        <template #default="scope">
          <span class="stock-name">{{ scope.row.stockName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="买卖情况" width="250">
        <template #default="scope">
          <TradeProgress
            :buy-amount="scope.row.buyAmount"
            :sell-amount="scope.row.sellAmount"
            :net-buy-amount="scope.row.netBuyAmount"
            :tooltip="true"
            :show-labels="true"
          />
        </template>
      </el-table-column>

      <el-table-column label="交易次数" width="100" align="center">
        <template #default="scope">
          <div class="trade-count">
            <div class="count-item">
              <span class="buy-count">买: {{ scope.row.buyCount }}次</span>
            </div>
            <div class="count-item">
              <span class="sell-count">卖: {{ scope.row.sellCount }}次</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="positionRatio" label="持仓比例" width="120" sortable="custom"
        :sort-method="sortByPositionRatio">
        <template #default="scope">
          <span class="position-ratio">{{ (scope.row.positionRatio).toFixed(2) }}%</span>
        </template>
      </el-table-column>

      <el-table-column label="浮盈" width="120" sortable="custom" :sort-method="sortByFloatLossPercentage">
        <template #default="scope">
          <span :class="{
            'float-loss-positive': scope.row.floatLossPercentage > 0,
            'float-loss-negative': scope.row.floatLossPercentage < 0,
            'float-loss-zero': scope.row.floatLossPercentage === 0
          }">
            {{ scope.row.floatLossPercentage > 0 ? '+' : '' }}{{ scope.row.floatLossPercentage.toFixed(2) }}%
          </span>
        </template>
      </el-table-column>





      <el-table-column label="价格走势（建仓位置）">
        <template #default="scope">
          <div class="chart-container" v-if="scope.row.chart && scope.row.chart.length > 0">
            <TradingChart :chartData="scope.row.chart" height="120px" />
          </div>
          <div v-else class="no-chart">
            <span>暂无数据</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="buyDate" label="买入时间" width="120" sortable>
        <template #default="scope">
          <span class="buy-date">{{ scope.row.buyDate }}</span>
        </template>
      </el-table-column>



      <!-- <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button link size="small" @click="handleViewDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-card>
</template>

<script setup>
import { computed, ref } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import TradingChart from './chart/TradingChart.vue'
import TradeProgress from '@/components/TradeProgress.vue'

// Props 定义
const props = defineProps({
  externalLoading: {
    type: Boolean,
    default: false
  },
  hotMoneyData: {
    type: Object,
    required: true
  }
})

// Emits 定义
const emit = defineEmits(['refresh'])

// 内部状态
const loading = ref(false)

// 计算属性：映射持仓数据
const holdingsData = computed(() => {
  // 使用传入的hotMoneyData中的day30数据
  if (props.hotMoneyData && props.hotMoneyData.day30) {
    return props.hotMoneyData.day30.map(item => ({
      stockCode: item.dbStock.code,
      stockName: item.stockName,
      buyAmount: item.buyAmount || 0,
      sellAmount: item.sellAmount || 0,
      netBuyAmount: item.netBuyAmount || 0,
      buyCount: item.buyInfo ? item.buyInfo.length : 0,
      sellCount: item.sellInfo ? item.sellInfo.length : 0,
      positionRatio: item.positionRatio || 0,
      floatLossPercentage: item.currentPrice && item.costPrice ?
        ((item.currentPrice - item.costPrice) / item.costPrice * 100) : 0,
      buyDate: item.buyDate,
      chart: item.chart || []
    }))
  }
  // 如果没有数据则返回空数组
  return []
})

// 刷新处理函数
const handleRefresh = () => {
  // 通知父组件刷新数据
  emit('refresh')
}


// 排序方法
const sortByPositionRatio = (a, b) => {
  return a.positionRatio - b.positionRatio
}

const sortByFloatLossPercentage = (a, b) => {
  return a.floatLossPercentage - b.floatLossPercentage
}


</script>

<style scoped>
.holdings-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stock-code {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 500;
  color: #409EFF;
}

.stock-name {
  font-weight: 500;
  color: #303133;
}

.position-ratio {
  color: #606266;
  font-size: 14px;
}

.buy-date {
  color: #606266;
  font-size: 14px;
  font-family: 'Monaco', 'Consolas', monospace;
}

/* 表格排序和加载状态优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.el-table th.is-sortable:hover {
  background-color: #e9ecef;
}

.el-table .sort-caret.ascending {
  border-bottom-color: #409eff;
}

.el-table .sort-caret.descending {
  border-top-color: #409eff;
}

.el-table__empty-text {
  color: #909399;
  font-size: 14px;
}

/* 行悬停效果 */
.el-table tbody tr:hover>td {
  background-color: #f5f7fa !important;
}

/* 当前行高亮 */
.el-table__body tr.current-row>td {
  background-color: #ecf5ff !important;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 8px;
}

.el-loading-spinner .el-loading-text {
  color: #409eff;
  font-weight: 500;
}


/* 交易次数样式 */
.trade-count {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.count-item {
  font-size: 12px;
  line-height: 1.2;
}

.buy-count {
  color: #67c23a;
  font-weight: 500;
}

.sell-count {
  color: #f56c6c;
  font-weight: 500;
}

/* 浮亏百分比样式 */
.float-loss-positive {
  color: #f56c6c;
  font-weight: 600;
}

.float-loss-negative {
  color: #67c23a;
  font-weight: 600;
}

.float-loss-zero {
  color: #909399;
  font-weight: 500;
}

:deep(.el-table) {
  font-family: 'Inter', 'HarmonyOS Sans SC', sans-serif;
}

:deep(.el-table th) {
  background-color: #F5F7FA;
  color: #909399;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #F5F7FA;
}

/* 图表容器样式 */
.chart-container {
  padding: 8px;
  border-radius: 4px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
}

.no-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 120px;
  color: #909399;
  font-size: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}
</style>